<template>
  <NuxtLayout name="manage-layout">
    <template #main>
      <div class="min-h-dvh flex justify-center">
        <div class="card bg-base-100 w-11/12 shadow-xl">
          <div class="card-body">
            <h4 class="card-title">AI 聊天助手</h4>
            <div class="flex flex-col gap-4">
              <!-- 聊天记录 -->
              <div class="chat-container bg-base-200 p-4 rounded-lg h-96 overflow-y-auto" ref="chatContainer">
                <div v-for="(message, index) in messages" :key="index"
                     class="chat" :class="message.role === 'user' ? 'chat-end' : 'chat-start'">
                  <div class="chat-header">
                    {{ message.role === 'user' ? '你' : 'AI' }}
                  </div>
                  <div class="chat-bubble" :class="message.role === 'user' ? 'chat-bubble-primary' : ''">
                    {{ message.content }}
                  </div>
                </div>
              </div>
              <!-- 输入框 -->
              <div class="flex gap-2">
                <input
                    v-model="userInput"
                    type="text"
                    placeholder="请输入你的问题"
                    class="input input-bordered w-full"
                    @keyup.enter="sendMessage"
                    :disabled="loading"
                />
                <button
                    class="btn btn-primary"
                    :disabled="loading || !userInput.trim()"
                    @click="sendMessage"
                >
                  <span v-if="loading" class="loading loading-spinner"></span>
                  {{ loading ? '发送中...' : '发送' }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </NuxtLayout>
</template>

<script setup>
import { ref, nextTick, onMounted, onUnmounted } from 'vue';

const userInput = ref('');
const messages = ref([]);
const loading = ref(false);
const chatContainer = ref(null);
let currentEventSource = null;

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick();
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
  }
};


const sendMessage = async () => {
  if (!userInput.value.trim() || loading.value) return;

  try {
    loading.value = true;
    const userMessage = userInput.value.trim();
    messages.value.push({ role: 'user', content: userMessage });
    await scrollToBottom();

    if (currentEventSource) {
      currentEventSource.close();
    }

    // 使用 URLSearchParams 处理参数
    const params = new URLSearchParams({
      question: userMessage
    });

    const url = `/api/v1/chat/request?${params}`;
    console.log('Connecting to:', url);

    currentEventSource = new EventSource(url);
    let aiResponse = '';

    currentEventSource.onopen = (event) => {
      console.log('SSE connection opened');
    };

    currentEventSource.onmessage = (event) => {
      console.log('Received:', event.data);
      try {
        if (event.data === '[DONE]') {
          currentEventSource.close();
          if (aiResponse.trim()) {
            messages.value.push({
              role: 'assistant',
              content: aiResponse.trim()
            });
            scrollToBottom();
          }
          loading.value = false;
        } else {
          const content = event.data;
          if (content && content.trim()) {
            aiResponse += content;
          }
        }
      } catch (error) {
        console.error('Error processing message:', error);
      }
    };

    currentEventSource.onerror = (error) => {
      console.error('SSE connection error:', error);
      currentEventSource.close();
      messages.value.push({
        role: 'assistant',
        content: '连接出错，请重试'
      });
      loading.value = false;
      scrollToBottom();
    };

    userInput.value = '';

  } catch (error) {
    console.error('Error in sendMessage:', error);
    messages.value.push({
      role: 'assistant',
      content: '发送消息时出错：' + error.message
    });
    loading.value = false;
    scrollToBottom();
  }
};
// 清理函数
onUnmounted(() => {
  if (currentEventSource) {
    currentEventSource.close();
  }
});
</script>

<style scoped>
.chat-container {
  scrollbar-width: thin;
  scrollbar-color: rgba(155, 155, 155, 0.5) transparent;
}

.chat-container::-webkit-scrollbar {
  width: 6px;
}

.chat-container::-webkit-scrollbar-track {
  background: transparent;
}

.chat-container::-webkit-scrollbar-thumb {
  background-color: rgba(155, 155, 155, 0.5);
  border-radius: 3px;
}
</style>